﻿using System.Collections.Generic;
using System.Linq;

namespace ComeSeeThis_MVC2.Models
{
    public class TireRepository
    {
        private readonly ComeSeeThisDBEntities _entities = new ComeSeeThisDBEntities();

        #region Query Methods

        public IQueryable<Tire> GetAllTires()
        {
            return _entities.Tires.OrderBy(x=>x.Company.CompanyName).ThenBy(x=>x.TireName);
        }
        
        public IQueryable<Tire> GetAllTiresByCompany(int companyId)
        {
            return _entities.Tires.Where(c => c.CompanyId == companyId).OrderBy(v => v.TireName);
        }
        
        public IQueryable<Tire> GetAllTiresByVehicleType(int vehicleTypeId)
        {
            var context = _entities;
            var result = from tires in context.Tires
                         from vehicleType in tires.VehicleTypes
                         where vehicleType.VehicleTypeId == vehicleTypeId
                         select tires;
            return result;
        }
        
        public bool TireVehicleTypeExists(int vehicleTypeId, int tireId)
        {
            var boo = _entities.Tires;
            var vehicleType = new VehicleTypeRepository().GetVehicleType(vehicleTypeId);

            var boo2 = from r in boo
                       where r.TireId == tireId && r.VehicleTypes.Contains(vehicleType)
                       select r;

            return boo2.ToList().Count > 0;
        }
            
        public Dictionary<VehicleType, Tire> VehicleTypeTire(int tireId)
        {
            var boo = _entities.Tires;
            //var vehicleType = new VehicleTypeRepository().GetVehicleType(vehicleTypeId);

            var results = from b in _entities.Tires
                          from c in b.VehicleTypes
                          where b.TireId == tireId
                          select  new {b, c};

            return results.ToDictionary(result => result.c, result => result.b);
        }

        public Tire GetTire(int tireId)
        {
            return _entities.Tires.SingleOrDefault(c => c.TireId == tireId);
        }

        public Tire GetLastTire()
        {
            return _entities.Tires.OrderByDescending(x=>x.TireId).First();
        }

        #endregion

        #region Insert / Delete Methods

        public void Add(Tire tire)
        {
            _entities.Tires.AddObject(tire);
        }

        public void Delete(Tire tire)
        {
            // Delete the tire
            _entities.Tires.DeleteObject(tire);
        }

        #endregion

        #region Persistance

        public void Save()
        {
            _entities.SaveChanges();
        }

        #endregion
    }
}